package com.ecommerce.gateway.filter;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class RouteValidator {

    // 不需要认证的路径列表
    private static final List<String> OPEN_API_ENDPOINTS = Arrays.asList(
            "/auth/login",
            "/auth/register",
            "/auth/refresh-token",
            "/api/auth/login",
            "/api/auth/register",
            "/api/auth/refresh-token",
            "/api/users/login",    // 用户服务登录接口
            "/api/users/register", // 用户服务注册接口
            "/api/users/sync",     // 用户数据同步接口
            "/api/users/sync-password/**", // 密码同步接口
            "/product/list",
            "/product/detail",
            "/product/category",
            "/product/categories",
            "/product/hot",
            "/product/search",
            "/categories",
            "/products",
            "/products/hot",
            "/api/categories",
            "/api/products",
            "/api/products/hot",
            "/api/orders/test",  // 订单服务测试接口（原始路径）
            "/orders/test"       // 订单服务测试接口（StripPrefix后的路径）
    );

    public Predicate<ServerHttpRequest> isSecured = request -> {
        String path = request.getPath().value();
        System.out.println("RouteValidator checking path: " + path);
        
        // 标准化路径，去除尾部斜杠（如果有）
        String normalizedPath = path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path;
        
        // 检查是否在开放路径列表中
        boolean isOpenEndpoint = OPEN_API_ENDPOINTS.stream().anyMatch(endpoint -> {
            // 标准化排除路径
            String normalizedEndpoint = endpoint.endsWith("/") && endpoint.length() > 1 ? 
                endpoint.substring(0, endpoint.length() - 1) : endpoint;
            
            // 精确匹配或路径前缀匹配
            boolean exactMatch = normalizedPath.equals(normalizedEndpoint);
            boolean prefixMatch = normalizedPath.startsWith(normalizedEndpoint + "/");
            
            return exactMatch || prefixMatch;
        });
        
        System.out.println("Path " + path + " is open endpoint: " + isOpenEndpoint + ", requires auth: " + !isOpenEndpoint);
        
        return !isOpenEndpoint;
    };
}